import tool.listPrint;
import tool.ListNode;
import tool.createList;

/**
 * @Description: 删除链表的倒数第 N 个结点
 * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 * @Date:Create in 15:07  2022/6/28
 */
public class removeNthFromEnd0019 {

    public static void main(String[] args) {
        int[] arr = new int[]{1, 2};
        ListNode head = createList.create_List(arr);
        listPrint.printListHead(head);
        System.out.println("**********");
        ListNode res = removeNthFromEnd1(head, 2);
        listPrint.printListHead(res);


    }


    public static ListNode removeNthFromEnd1(ListNode head, int n) {
        ListNode pre = head;
        ListNode cur = head;
        int a = 1;
        while (cur.next != null) {
            cur = cur.next;
            a++;
        }
        int b = a - n;
        int c = 1;
        if (b == 0) {
            ListNode head_v = new ListNode(0);
            head_v.next = head.next;
            return head_v.next;
        } else {
            ListNode tar = head;
            while (tar.next != null) {
                pre = tar;
                tar = tar.next;
                if (c == b) {
                    pre.next = tar.next;
                }
                c++;
            }
        }
        return head;

    }
    //双指针的经典应用
    public static ListNode removeNthFromEnd2(ListNode head, int n) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;

        ListNode slow = dummy;
        ListNode fast = dummy;
        while (n-- > 0) {
            fast = fast.next;
        }
        // 记住 待删除节点slow 的上一节点
        ListNode prev = null;
        while (fast != null) {
            prev = slow;
            slow = slow.next;
            fast = fast.next;
        }
        // 上一节点的next指针绕过 待删除节点slow 直接指向slow的下一节点
        prev.next = slow.next;
        // 释放 待删除节点slow 的next指针, 这句删掉也能AC
        slow.next = null;

        return dummy.next;
    }
}
